package com.wbu.estatemanagement.service.impl;

import com.wbu.estatemanagement.dao.BuildingMapper;
import com.wbu.estatemanagement.dao.CommunityMapper;
import com.wbu.estatemanagement.dao.RepairMapper;
import com.wbu.estatemanagement.dao.UserMapper;
import com.wbu.estatemanagement.domain.Building;
import com.wbu.estatemanagement.domain.Community;
import com.wbu.estatemanagement.domain.Repair;
import com.wbu.estatemanagement.domain.User;
import com.wbu.estatemanagement.service.RepairService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RepairServiceImpl implements RepairService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RepairMapper repairMapper;
    @Autowired
    CommunityMapper communityMapper;
    @Autowired
    BuildingMapper buildingMapper;

    @Override
    public Repair findRepair(Integer userId) {

        List<Repair> repairs = repairMapper.selectAll();
        List<Repair> collect = repairs.stream().filter(s -> s.getOwnerId() == userId).collect(Collectors.toList());
        Repair repair = collect.get(collect.size()-1);
        String status = repair.getStatus();
        if (status.equals("0")){
            repair.setStatus("待修理");
        }else {
            repair.setStatus("修理完毕");
        }
        return repair;
    }

    @Override
    public Boolean addRepair(Repair repair) {
        //用户名称
        String ownerName = repair.getOwnerName();
        //用户集合
        List<User> users = userMapper.selectAll();
        //在集合中取适配数据,设置用户id
        for (User user:users){
            if (user.getName().equals(ownerName)){
                Integer userId = user.getId();
                repair.setOwnerId(userId);
            }
        }
        //社区名称
        String communityName = repair.getCommunityName();
        List<Community> communities = communityMapper.selectAll();
        //设置社区id
        for (Community community: communities){
            if (community.getName().equals(communityName)){
                Integer communityId = community.getId();
                repair.setCommunityId(communityId);
            }
        }
        //楼栋名称
        String buildingName = repair.getBuildingName();
        //设置楼栋id
        List<Building> buildings = buildingMapper.selectAll();
        for(Building building:buildings){
            if (building.getName().equals(buildingName)){
                Integer buildingId = building.getId();
                repair.setBuildingId(buildingId);
            }
        }
        repair.setStatus("0");
        int addRepair = repairMapper.insert(repair);
        if (addRepair==1){
            return true;
        }
        return false;
    }


}
